#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015  Data Enlighten Technology (Beijing) Co.,Ltd


import re
import base64
import Lib.Logger.log4py as logging
from mj_parser import common_errors


class PorscheWebParser:
    default_result = {
        'model': '',
        'year': '',
        'manufacture_date': '',
        'type': '',
        'engine': '',
        'transmission': '',
        'pr_list': '',
        'content': ''
    }

    def __init__(self, root_dir):
        self.root_dir = root_dir
        self.logger = logging.get_logger("crawler", "PorscheWebParser")

    def find_string(self, HTML, name):
        p = re.compile('<th>' + name + '</th><td>.+?</td>', re.S)
        HTML_Div_CHN_li = p.findall(HTML)
        if HTML_Div_CHN_li is not None and len(HTML_Div_CHN_li) > 0:
            return HTML_Div_CHN_li[0].replace('<th>' + name + '</th><td>', '').replace('</tr>', '').replace('</td>',
                                                                                                            '').replace(
                '\t', '').replace('\n', '').replace('&nbsp;', '').replace('\xa0', '')
        else:
            return ''

    def find_content_template(self, HTML, name):
        p = re.compile('<input type="hidden" name="' + name + '" value=".+?" id="catalog1"', re.S)
        HTML_Div_CHN_li = p.findall(HTML)
        if HTML_Div_CHN_li is not None and len(HTML_Div_CHN_li) > 0:
            return HTML_Div_CHN_li[0].replace('<input type="hidden" name="' + name + '" value="', '').replace(
                '" id="catalog1"', '')
        else:
            return ''

    def parse(self, file_name):
        code = common_errors.ERR_SUCCESS
        try:
            result_list = {}
            fobj = open(file_name, encoding='utf_8_sig')
            HTML = fobj.read()

            if HTML.find('没有找到您搜索的车辆识别代码的数据。该车辆识别代码不存在或者尚未输入相关车辆数据') >= 0:
                b = common_errors.ERR_NO_VIN
                return b, result_list

            result_list['model'] = self.find_string(HTML, '车型名称')
            result_list['year'] = self.find_string(HTML, '年份')
            result_list['manufacture_date'] = self.find_string(HTML, '年份')
            result_list['type'] = self.find_string(HTML, '隆等濬梗')
            result_list['engine'] = self.find_string(HTML, '发动机代码')
            result_list['transmission'] = self.find_string(HTML, '变速器代码')

            result_list['content'] = self.find_content_template(HTML, 'catalog').zfill(3)
            result_list['raw_content'] = base64.b64encode(HTML.encode('utf-8')).decode('utf-8')

            p = re.compile('<td colspan="2" style="font-weight: bold; font-size: x-large;">MI 编号</td></tr>.+?</tbody>',
                           re.S)
            res1 = p.findall(HTML)
            p1 = re.compile('<th>.+?</th>', re.S)
            HTML_Div_CHN_li = p1.findall(res1[0])
            if HTML_Div_CHN_li is not None and len(HTML_Div_CHN_li) > 0:
                li = []
                for x in HTML_Div_CHN_li:
                    x = x.replace('<th>', '').replace('</th>', '').replace('\t', '').replace('\n', '')
                    li.append(x)
                result_list['pr_list'] = '|'.join(li)
            else:
                result_list['pr_list'] = ''
                b = common_errors.ERR_NO_CONTENT
                self.logger.error('pr_list is empty.')

        except Exception as ex:
            self.logger.error(ex)
            code = common_errors.ERR_UNKNOWN
        return code, result_list

    def get_default_result(self):
        return PorscheWebParser.default_result.copy()

if __name__ == '__main__':
    parser = PorscheWebParser()
    parser.parse('porsche\WP0AB2996FS124430.html')
